package com.hh.tc.ui.todo.editItem

import androidx.databinding.ObservableArrayList
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.hh.base.ui.BaseViewModel
import com.hh.base.ui.bridge.Event
import com.hh.base.widget.dialog.MultifunctionDialog
import com.hh.db.core.ObjectBoxUtil
import com.hh.db.core.ObjectBoxUtil.queryList
import com.hh.db.entity.TODODetail_
import com.hh.db.entity.TODOItem
import com.hh.tc.ui.todo.addItem.AddItemDialog

/**
 * Create By hHui on 2025/4/16 14:18
 *
 * @description
 */
class EditTodoItemViewModel(handle: SavedStateHandle) : BaseViewModel(handle), AddItemDialog.OnItemListener {
    private val _addItemDialogStatus = MutableLiveData<Event<Triple<Boolean, TODOItem?, AddItemDialog.OnItemListener?>>>()
    val addItemDialogStatus: LiveData<Event<Triple<Boolean, TODOItem?, AddItemDialog.OnItemListener?>>> = _addItemDialogStatus

    val items = ObservableArrayList<TODOItem>()

    override fun initData() {
        refreshData()
    }

    fun deleteItem(item: TODOItem) {
        alertOption(msg = "确定删除${item.name}吗？", clickListener = object : MultifunctionDialog.AlertClickListener {
            override fun onConfirm(content: String?) {
                // 删除item
                ObjectBoxUtil.todoItemBox.remove(item.id)
                //删除item对应的detail
                ObjectBoxUtil.todoDetailBox.queryList(TODODetail_.itemId.equal(item.id)).forEach {
                    ObjectBoxUtil.todoDetailBox.remove(it.id)
                }
                refreshData()
                showToast("删除成功")
            }

            override fun onCancel() = Unit
        })
    }

    fun editTodoItem(item: TODOItem) {
        _addItemDialogStatus.value = Event(Triple(true, item, this))
    }

    fun addTodoItem() {
        _addItemDialogStatus.value = Event(Triple(true, null, this))
    }

    fun refreshData() {
        items.clear()
        items.addAll(ObjectBoxUtil.todoItemBox.all)
    }

    override fun onError(message: String) {
    }

    override fun onSuccess() {
        refreshData()
    }
}